package com.williambucciero.mobilemuseum;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class BackgroundAlarm {
	private Context ctxt = null;
	
	public BackgroundAlarm(Context ctxt){
		this.ctxt = ctxt;
	}
	
	public void fireOneTimeAlarm(){
    	AlarmManager myAlarmMgr = (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
    	myAlarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt,BackgroundAlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT));
    }
	
	public void fireRepeatingAlarm(){
    	AlarmManager myAlarmMgr = (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
    	myAlarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, calculateTimeDifference(), AlarmManager.INTERVAL_DAY ,PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt,BackgroundAlarmReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT));
	}

	/* Unused right now (meant for canceling alarm a feature that has been removed)
	public void cancelAllAlarm(){
		if(isRunning()){
		 	AlarmManager myAlarmMgr = (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
		    myAlarmMgr.cancel(PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt, BackgroundAlarmReceiver.class), PendingIntent.FLAG_NO_CREATE));
		}
	}
	
	public boolean isRunning(){
    	return (PendingIntent.getBroadcast(ctxt, 0, new Intent(ctxt, BackgroundAlarmReceiver.class), PendingIntent.FLAG_NO_CREATE)!=null);
	} */
	
	private long calculateTimeDifference(){
    	Calendar cal = Calendar.getInstance();
    	if(!(cal.get(Calendar.HOUR)<3 && cal.get(Calendar.AM_PM)==Calendar.AM)){ cal.set(Calendar.DATE, cal.get(Calendar.DATE)+1); }
    	cal.set(Calendar.HOUR, 3);
    	cal.set(Calendar.AM_PM, Calendar.AM);
		Calendar c = Calendar.getInstance();

		DebugReporter reporter = new DebugReporter(ctxt);
		reporter.writeToFile("BA: Calculated Time Difference to be " + ((Long)(cal.getTime().getTime() - c.getTime().getTime())).toString());
		
		return cal.getTime().getTime() - c.getTime().getTime();
	}
}
